package svc

import (
	"encoding/json"
	"fmt"
	"github.com/shugen/models"
)

//Insert
func (s *Svc) InsertSelf(self *models.Self) error {

	if _, err := s.Engine.Insert(self); err != nil {
		fmt.Println("新增失败:", self, err)
		return err
	}
	return nil
}

//Update
func (s *Svc) UpdateSelf(self *models.Self) (*models.Self, error) {

	ss := &models.Self{}
	//title和type不需要更新
	affect, err := s.Engine.ID(string(self.SelfId)).Omit("type").Omit("title").Omit("phone_number").Update(self)
	if err != nil {
		return nil, err
	}
	if affect > 0 {
		s.Engine.ID(string(self.SelfId)).Get(ss)
	}
	return ss, nil
}

//Select
func (s *Svc) SelectSelf(self *models.Self) (*models.Self, error) {

	ss := &models.Self{}

	if _, err := s.Engine.Where("type = ? and phone_number = ?", self.Type, self.PhoneNumber).Get(ss); err != nil {
		return nil, err
	}
	return ss, nil
}

//Select List
func (s *Svc) ListSelf(self *models.Self) ([]*models.Self, error) {

	var list []*models.Self

	if err := s.Engine.Where("type = ?", self.Type).Find(&list); err != nil {
		return nil, err
	}
	return list, nil
}

func (s *Svc) self_common(self *models.Self) ([]*Desc, error) {

	desc := make([]*Desc, 0)
	rsp, err := s.SelectSelf(self)
	if err != nil {
		return desc, err
	}
	err = json.Unmarshal([]byte(rsp.Desc), &desc)
	if err != nil {
		return desc, err
	}
	return desc, nil
}
